package com.kokuma.drawsprite.ftp.util;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.kokuma.drawsprite.common.StaticValue;
import com.kokuma.drawsprite.ftp.models.CfgFtp;
import com.kokuma.drawsprite.ftp.models.CfgFtpPath;
import com.kokuma.drawsprite.ftp.services.interfaces.ICfgFtpPathServices;
import com.kokuma.drawsprite.ftp.services.interfaces.ICfgFtpServices;

import javax.annotation.Resource;
import javax.print.DocFlavor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Created by xiao on 2018/1/21.
 */
public class FTPUtil {

	private static Logger logger = LoggerFactory.getLogger(FTPUtil.class);
	private String ip;
	private int port;
	private String user;
	private String pwd;
	private String remotePath;
	private String cfgPathCode;
	private String proxyUrl;

	private FTPClient ftpClient;

	public FTPUtil(String ftpPathCode) {
		ICfgFtpPathServices cfgFtpPathServices=(ICfgFtpPathServices) SpringContextUtil.getBean("cfgFtpPathServices");
		ICfgFtpServices cfgFtpServices=(ICfgFtpServices) SpringContextUtil.getBean("cfgFtpServices");

		List<CfgFtpPath> cfgFtpPathList = cfgFtpPathServices.getCfgFtpPath(ftpPathCode);
		if (cfgFtpPathList != null && cfgFtpPathList.size() > 0) {
			for (int i = 0; i < cfgFtpPathList.size(); i++) {
				CfgFtpPath path = cfgFtpPathList.get(i);
				List<CfgFtp> ftpList = cfgFtpServices.getCfgFtp(path.getCfgFtpCode());
				if (ftpList != null && ftpList.size() > 0) {
					CfgFtp ftp = ftpList.get(0);
					this.setIp(ftp.getFtpHost());
					this.setUser(ftp.getFtpUser());
					this.setPwd(ftp.getFtpPwd());
					this.setPort(Integer.parseInt(ftp.getFtpPort()));
					this.setRemotePath(path.getRemotePath());
					this.setProxyUrl(ftp.getProxyUrl());
				}
			}
		}
		this.cfgPathCode = ftpPathCode;
	}

	public FTPUtil(String ip, int port, String user, String pwd, String remotePath) {
		this.ip = ip;
		this.port = port;
		this.pwd = pwd;
		this.user = user;
		this.remotePath = remotePath;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public FTPClient getFtpClient() {
		return ftpClient;
	}

	public void setFtpClient(FTPClient ftpClient) {
		this.ftpClient = ftpClient;
	}

	public String getRemotePath() {
		return remotePath;
	}

	public void setRemotePath(String remotePath) {
		this.remotePath = remotePath;
	}
	
	

	public String getCfgPathCode() {
		return cfgPathCode;
	}

	public void setCfgPathCode(String cfgPathCode) {
		this.cfgPathCode = cfgPathCode;
	}
	
	



	public String getProxyUrl() {
		return proxyUrl;
	}

	public void setProxyUrl(String proxyUrl) {
		this.proxyUrl = proxyUrl;
	}
	
	@Override
	public String toString() {
		return "FTPUtil [ip=" + ip + ", port=" + port + ", user=" + user + ", pwd=" + pwd + ", remotePath=" + remotePath
				+ ", cfgPathCode=" + cfgPathCode + ", proxyUrl=" + proxyUrl + ", ftpClient=" + ftpClient + "]";
	}

	/**
	 * 对外暴露的上传文件方法
	 * 
	 * @param fileList
	 * @return
	 */

	public boolean uploadFile(List<File> fileList) throws IOException {
		boolean uploaded = true;
		FileInputStream fis = null;
		// 连接FTP服务器
		if (connectServer(this.getIp(), this.getUser(), this.getPwd(), this.getPort())) {
			try {
				ftpClient.changeWorkingDirectory(this.remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding(StaticValue.CFG_FTP_ENCODING);
				// 设置成二进制格式可以防止乱码
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				// 被动模式存储
				ftpClient.enterLocalPassiveMode();
				ftpClient.setConnectTimeout(StaticValue.CFG_FTP_CLIENT_TIMEOUT);
				// 遍历文件存储
				for (File fileItem : fileList) {
					// 把文件转成文件流
					fis = new FileInputStream(fileItem);
					// 调用storeFile方法存储
					ftpClient.storeFile(fileItem.getName(), fis);
				}
				logger.debug("文件上传成功");
			} catch (IOException e) {
				logger.error("上传文件异常", e);
				uploaded = false;

			} finally {
				// 关闭连接和文件流
				fis.close();
				ftpClient.disconnect();

			}
		}
		return uploaded;
	}

	/**
	 * 对外暴露的上传文件方法
	 * 
	 * @param fileList
	 * @return
	 */

	public boolean uploadFile(File file) throws IOException {
		boolean uploaded = true;
		FileInputStream fis = null;
		// 连接FTP服务器
		if (connectServer(this.getIp(), this.getUser(), this.getPwd(), this.getPort())) {
			try {
				ftpClient.changeWorkingDirectory(this.remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding(StaticValue.CFG_FTP_ENCODING);
				// 设置成二进制格式可以防止乱码
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				// 被动模式存储
				ftpClient.enterLocalPassiveMode();
				ftpClient.setConnectTimeout(StaticValue.CFG_FTP_CLIENT_TIMEOUT);

				// 把文件转成文件流
				fis = new FileInputStream(file);
				// 调用storeFile方法存储
				ftpClient.storeFile(file.getName(), fis);
				logger.debug("文件上传成功");
			} catch (IOException e) {
				logger.error("上传文件异常", e);
				uploaded = false;

			} finally {
				// 关闭连接和文件流
				fis.close();
				ftpClient.disconnect();

			}
		}
		return uploaded;
	}

	/**
	 * 对外暴露的上传文件方法
	 * 
	 * @param fileList
	 * @return
	 */

	public boolean uploadFile(MultipartFile file) throws IOException {
		boolean uploaded = true;
		InputStream fis = null;
		// 连接FTP服务器
		if (connectServer(this.getIp(), this.getUser(), this.getPwd(), this.getPort())) {
			try {
				ftpClient.changeWorkingDirectory(this.remotePath);
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding(StaticValue.CFG_FTP_ENCODING);
				// 设置成二进制格式可以防止乱码
				ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
				// 被动模式存储
				ftpClient.enterLocalActiveMode();
				ftpClient.setConnectTimeout(StaticValue.CFG_FTP_CLIENT_TIMEOUT);
				FTPFile[] files = ftpClient.listFiles();
				// 把文件转成文件流
				fis = file.getInputStream();
				// 调用storeFile方法存储
				ftpClient.storeFile(file.getOriginalFilename(), fis);
				logger.debug("上传文件成功");
			} catch (IOException e) {
				logger.error("上传文件异常", e);
				uploaded = false;

			} finally {
				// 关闭连接和文件流
				fis.close();
				ftpClient.disconnect();

			}
		}
		return uploaded;
	}

	/**
	 * 连接FTP服务器
	 * 
	 * @param ip
	 * @param user
	 * @param pwd
	 * @return
	 */
	private boolean connectServer(String ip, String user, String pwd, int port) {
		boolean isSuccess = false;
		ftpClient = new FTPClient();
		try {
			logger.debug("连接服务器开始" + ip + "端口" + port);
			ftpClient.connect(ip, port);
			;
			isSuccess = ftpClient.login(user, pwd);
			logger.debug("登录成功");
		} catch (IOException e) {
			logger.error("FTP服务器连接失败", e);

		}
		return isSuccess;
	}

}